package com.keson.blue;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;


public class BluetoothReceiver extends BroadcastReceiver{
 
	String pin = "123456";  //此处为你要连接的蓝牙设备的初始密钥，一般为1234或0000
	public BluetoothReceiver() {
		
	}
 
	//广播接收器，当远程蓝牙设备被发现时，回调函数onReceiver()会被执行 
	@Override
	public void onReceive(Context context, Intent intent) {
		
		String action = intent.getAction(); //得到action
		Log.e("action1=", action);
		BluetoothDevice btDevice=null;  //创建一个蓝牙device对象
		 // 从Intent中获取设备对象
		btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

		if(BluetoothDevice.ACTION_FOUND.equals(action)){  //发现设备
			Log.e("发现设备:", "["+btDevice.getName()+"]"+":"+btDevice.getAddress());
			
			if(btDevice.getName().contains("rksdk")){//设备如果有多个，第一个搜到的那个会被尝试。
				if (btDevice.getBondState() == BluetoothDevice.BOND_NONE) {
					Log.e("ywq", "attemp to bond:"+"["+btDevice.getName()+"]");
					try {
						//通过工具类ClsUtils,调用createBond方法
						ClsUtils.createBond(btDevice.getClass(), btDevice);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }
			}else if(btDevice.getName().contains("Android Bluedroid")){
				if (btDevice.getBondState() == BluetoothDevice.BOND_NONE) {
					Log.e("ywq", "attemp to bond:"+"["+btDevice.getName()+"]");
					try {
						//通过工具类ClsUtils,调用createBond方法
						ClsUtils.createBond(btDevice.getClass(), btDevice);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}else{
				Log.e("error", "Is faild");
			}
		}else if(action.equals("android.bluetooth.device.action.PAIRING_REQUEST")){ //再次得到的action，会等于PAIRING_REQUEST
			Log.e("action2=", action);
			Bundle extras = intent.getExtras();
			Log.i("TAG", "-->"+extras.toString());
			Object device = extras.get("android.bluetooth.device.extra.DEVICE");
			Object pairkey = extras.get("android.bluetooth.device.extra.PAIRING_KEY");
			Log.i("TAG", "device-->"+String.valueOf(device));
			Log.i("TAG", "pairkey-->"+String.valueOf(pairkey));
			String key = String.valueOf(pairkey);
			if(key.length()<6){
				for (int i = 0; i < 6-key.length(); i++) {
					key = "0"+key;
				}
			}
			Log.i("TAG", "pairkey-->"+key);
			System.out.println(btDevice.getName());
//			if(btDevice.getName().contains("rksdk")){

				Log.e("here", "OKOKOK");
				
				try {
					//1.确认配对
//					btDevice.setPairingConfirmation(true);
					ClsUtils.setPairingConfirmation(btDevice.getClass(), btDevice, true);
					//2.终止有序广播
					Log.i("order...", "isOrderedBroadcast:"+isOrderedBroadcast()+",isInitialStickyBroadcast:"+isInitialStickyBroadcast());
					abortBroadcast();//如果没有将广播终止，则会出现一个一闪而过的配对框。
					//3.调用setPin方法进行配对...

					boolean ret = ClsUtils.setPin(btDevice.getClass(), btDevice, key);
//					System.out.println(btDevice.setPin(key.getBytes()));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

//			}else
//				Log.e("提示信息", "这个设备不是目标蓝牙设备");
			
		}else if(action.equals("android.bluetooth.device.action.ACL_CONNECTED")){
			//启动蓝牙通信服务
			BluetoothServer bluetoothServer = new BluetoothServer(new BaseBluetooth.BTListener() {
				private BluetoothServer bluetoothServer;
				@Override
				public void init(BluetoothServer server) {
					bluetoothServer = server;
				}

				@Override
				public void socketNotify(int state, Object obj) {
					if (state == MSG_RECEIVED) {
						JSONObject json = JSONObject.parseObject(String.valueOf(obj));
						System.out.println(json.toJSONString());
						try {
//							NetConfigUtil.wifiConfig(context,json.getBooleanValue("dhcp"),json.getString("ip"),json.getString("gate"),json.getString("dns1"),json.getString("dns2"));
//							System.out.println(WifiUtil.connect("KESON", "chinakeson", WifiUtil.WifiCipherType.WIFICIPHER_WPA));
							switch (json.getString("action")) {
								case "getWifiInfo":
									JSONObject jsonObject = new JSONObject();
									jsonObject.put("action","answerWifiInfo");
									jsonObject.put("ssid",WifiUtil.getSSID());
									jsonObject.put("net",StateUtil.isWifiConnected());
									bluetoothServer.sendMsg(jsonObject.toJSONString());
									break;
								case "setWifiInfo":
									WifiUtil.connect(json.getString("ssid"), json.getString("password"), WifiUtil.WifiCipherType.WIFICIPHER_WPA);
									jsonObject = new JSONObject();
									jsonObject.put("action","ok");
									bluetoothServer.sendMsg(jsonObject.toJSONString());
									break;
								case "getEthInfo":
									context.sendBroadcast(new Intent("temolin.intent.action.ETH_GET"));
									Thread.sleep(1000);
									jsonObject = new JSONObject();
									jsonObject.put("action","answerEthInfo");
									jsonObject.put("type",StateUtil.getProperty("tml.eth.ipType","").toLowerCase());
									JSONObject info = StateUtil.getEtherNetInfo();
									String ipaddr = StateUtil.getProperty("tml.eth.staticIp","");
									ipaddr = ipaddr.equals("")&&info!=null?info.getString("ip"):ipaddr;
									jsonObject.put("ip",ipaddr.split("/")[0]);
									String gate = StateUtil.getProperty("tml.eth.staticGateWayIp","");
									gate = gate.equals("")&&info!=null?info.getString("gateway"):gate;
									jsonObject.put("gateway",gate);
									String dnsOne = StateUtil.getProperty("tml.eth.staticDNS1","");
									dnsOne = dnsOne.equals("")&&info!=null?info.getString("dns1"):dnsOne;
									jsonObject.put("dns1",dnsOne);
									String dnsTwo = StateUtil.getProperty("tml.eth.staticDNS2", "");
									dnsTwo = dnsTwo.equals("")&&info!=null?info.getString("dns2"):dnsTwo;
									jsonObject.put("dns2",dnsTwo);
									jsonObject.put("net",StateUtil.isEtherNetConnected());
									bluetoothServer.sendMsg(jsonObject.toJSONString());
									break;
								case "setEthInfo":
									if(json.getString("type").equals("DHCP")){
										StateUtil.setProperty("tml.eth.ipType",json.getString("type"));
									}else{
										StateUtil.setProperty("tml.eth.ipType",json.getString("type"));
										StateUtil.setProperty("tml.eth.staticIp",json.getString("ip"));
										StateUtil.setProperty("tml.eth.staticGateWayIp",json.getString("gateway"));
										StateUtil.setProperty("tml.eth.staticDNS1",json.getString("dns1"));
										StateUtil.setProperty("tml.eth.staticDNS2",json.getString("dns2"));
									}
									context.sendBroadcast(new Intent("temolin.intent.action.ETH_UPDATE"));
									jsonObject = new JSONObject();
									jsonObject.put("action","ok");
									bluetoothServer.sendMsg(jsonObject.toJSONString());
//									DeviceControlUtil.reboot();
									break;
								case "getDevStatus":
									jsonObject = StateUtil.getDevStatus();
									jsonObject.put("action","answerDevStatus");
									bluetoothServer.sendMsg(jsonObject.toJSONString());
									break;
								case "getConfig":
									Constant.readConfig();
									jsonObject = new JSONObject();
									JSONObject infoJson = Constant.getInfoJsonObject();
									JSONObject configJson = Constant.getConfigJsonObject();
									jsonObject.put("action","answerConfig");
									jsonObject.put("info",infoJson);
									jsonObject.put("config",configJson);
									System.out.println("????????"+jsonObject.toJSONString());
									bluetoothServer.sendMsg(jsonObject.toJSONString());
									break;
								case "setConfig":
									try{
										Constant.parseCheck(json.getJSONObject("config"),json.getJSONObject("info"));
										Constant.updateConfigToFile(json.getJSONObject("config"),json.getJSONObject("info"));
										jsonObject = new JSONObject();
										jsonObject.put("action","ok");
										bluetoothServer.sendMsg(jsonObject.toJSONString());
										context.sendBroadcast(new Intent().setPackage("com.keson.guard").setAction("com.keson.eq.restartApp"));
									}catch (Exception e){
										e.printStackTrace();
										jsonObject = new JSONObject();
										jsonObject.put("action","error");
										bluetoothServer.sendMsg(jsonObject.toJSONString());
									}
									break;
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					} else {
						System.out.println(state + ":" + String.valueOf(obj));
					}
				}
			});
		}
	}
}